from django.db import models
from django.contrib.auth.models import User as DjangoUser
from django.utils import timezone


# 公司档案表
class Company(models.Model):
    INDUSTRY_CHOICES = [
        ('tech', '科技'),
        ('finance', '金融'),
        ('education', '教育'),
        ('healthcare', '医疗'),
        ('retail', '零售'),
        ('manufacturing', '制造业'),
        ('service', '服务业'),
        ('other', '其他'),
    ]

    name = models.CharField(max_length=200, verbose_name='公司名称', db_comment='公司名称')
    legal_person = models.CharField(max_length=100, verbose_name='法人代表', db_comment='法人代表')
    registration_number = models.CharField(max_length=100, unique=True, verbose_name='统一社会信用代码', db_comment='统一社会信用代码')
    industry = models.CharField(max_length=50, choices=INDUSTRY_CHOICES, verbose_name='所属行业', db_comment='所属行业')
    registered_capital = models.DecimalField(max_digits=15, decimal_places=2, verbose_name='注册资本', db_comment='注册资本')
    registration_date = models.DateField(verbose_name='注册日期', db_comment='注册日期')
    address = models.CharField(max_length=500, verbose_name='公司地址', db_comment='公司地址')
    contact_phone = models.CharField(max_length=50, verbose_name='联系电话', db_comment='联系电话')
    contact_email = models.EmailField(verbose_name='联系邮箱', db_comment='联系邮箱')
    description = models.TextField(blank=True, null=True, verbose_name='公司简介', db_comment='公司简介')
    created_at = models.DateTimeField(default=timezone.now, verbose_name='创建时间', db_comment='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间', db_comment='更新时间')

    class Meta:
        db_table = 'mentorx_companies'
        verbose_name = '公司档案'
        verbose_name_plural = '公司档案'
        db_table_comment = '公司档案表'

    def __str__(self):
        return self.name


# 部门表
class Department(models.Model):
    name = models.CharField(max_length=255, verbose_name='部门名称', db_comment='部门名称')
    manager = models.CharField(max_length=255, verbose_name='部门经理', db_comment='部门经理')
    description = models.TextField(blank=True, null=True, verbose_name='部门描述', db_comment='部门描述')
    company = models.ForeignKey(
        Company,
        on_delete=models.CASCADE,
        related_name='departments',
        verbose_name='所属公司',
        db_comment='所属公司ID'
    )
    created_at = models.DateTimeField(default=timezone.now, verbose_name='创建时间', db_comment='创建时间')

    class Meta:
        db_table = 'mentorx_departments'
        verbose_name = '部门'
        verbose_name_plural = '部门'
        db_table_comment = '部门表'

    def __str__(self):
        return f"{self.company.name} - {self.name}"


# 收支科目表
class FinanceCategory(models.Model):
    TYPE_CHOICES = [
        ('income', '收入'),
        ('expense', '支出'),
    ]

    name = models.CharField(max_length=100, verbose_name='科目名称', db_comment='科目名称')
    type = models.CharField(
        max_length=10,
        choices=TYPE_CHOICES,
        verbose_name='收支类型',
        db_comment='收支类型:income收入,expense支出'
    )
    parent = models.ForeignKey(
        'self',
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        related_name='children',
        verbose_name='上级科目',
        db_comment='上级科目ID'
    )
    description = models.TextField(blank=True, null=True, verbose_name='科目说明', db_comment='科目说明')
    created_at = models.DateTimeField(default=timezone.now, verbose_name='创建时间', db_comment='创建时间')

    class Meta:
        db_table = 'mentorx_finance_categories'
        verbose_name = '收支科目'
        verbose_name_plural = '收支科目'
        db_table_comment = '收支科目表'

    def __str__(self) -> str:
        if self.parent:
            return f"{self.parent.name} > {self.name}"
        return str(self.name)


# 用户扩展信息表
class UserProfile(models.Model):
    ROLE_CHOICES = [
        ('admin', '管理员'),
        ('manager', '部门经理'),
        ('employee', '职员'),
    ]

    user = models.OneToOneField(
        DjangoUser,
        on_delete=models.CASCADE,
        related_name='profile',
        verbose_name='用户',
        db_comment='关联用户'
    )
    phone = models.CharField(max_length=20, unique=True, verbose_name='手机号', db_comment='手机号')
    role = models.CharField(
        max_length=10,
        choices=ROLE_CHOICES,
        default='employee',
        verbose_name='角色',
        db_comment='用户角色'
    )
    # 将部门关联改为可为空，因为用户可能还没有分配部门
    department = models.ForeignKey(
        Department,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='users',
        verbose_name='所属部门',
        db_comment='所属部门'
    )
    # 添加与公司的直接关联
    company = models.ForeignKey(
        Company,
        on_delete=models.CASCADE,
        related_name='users',
        verbose_name='所属公司',
        db_comment='所属公司ID'
    )
    hire_date = models.DateTimeField(verbose_name='入职日期', db_comment='入职日期')

    class Meta:
        db_table = 'mentorx_user_profiles'
        verbose_name = '用户档案'
        verbose_name_plural = '用户档案'
        db_table_comment = '用户扩展信息表'

    def __str__(self) -> str:
        company_name = self.company.name if self.company else '无公司'
        dept_name = self.department.name if self.department else '无部门'
        # 使用更安全的方式获取用户名
        if hasattr(self.user, 'get_full_name') and self.user.get_full_name():
            user_name = self.user.get_full_name()
        else:
            user_name = getattr(self.user, 'username', '未知用户')
        return f"{user_name} ({company_name} - {dept_name})"


# 财务流水表
class FinanceRecord(models.Model):
    SOURCE_CHOICES = [
        ('manual', '手动录入'),
        ('import', '导入'),
    ]

    date = models.DateField(verbose_name='交易日期', db_comment='交易日期')
    # 添加与公司的直接关联
    company = models.ForeignKey(
        Company,
        on_delete=models.CASCADE,
        related_name='finance_records',
        verbose_name='所属公司',
        db_comment='所属公司ID'
    )
    department = models.ForeignKey(
        Department,
        on_delete=models.CASCADE,
        related_name='finance_records',
        verbose_name='所属部门',
        db_comment='所属部门ID'
    )
    category = models.ForeignKey(
        FinanceCategory,
        on_delete=models.CASCADE,
        related_name='finance_records',
        verbose_name='收支科目',
        db_comment='收支科目ID'
    )
    user_profile = models.ForeignKey(
        UserProfile,
        on_delete=models.CASCADE,
        related_name='finance_records',
        verbose_name='录入人',
        db_comment='录入人ID'
    )
    amount = models.DecimalField(
        max_digits=15,
        decimal_places=2,
        verbose_name='金额',
        db_comment='金额'
    )
    description = models.TextField(blank=True, null=True, verbose_name='备注说明', db_comment='备注说明')
    source = models.CharField(
        max_length=10,
        choices=SOURCE_CHOICES,
        default='manual',
        verbose_name='数据来源',
        db_comment='数据来源:manual手动录入,import导入'
    )
    created_at = models.DateTimeField(default=timezone.now, verbose_name='创建时间', db_comment='创建时间')

    class Meta:
        db_table = 'mentorx_finance_records'
        verbose_name = '财务流水'
        verbose_name_plural = '财务流水'
        ordering = ['-date', '-created_at']
        db_table_comment = '财务流水表'

    def __str__(self) -> str:
        company_name = getattr(self.company, 'name', '未知公司')
        dept_name = getattr(self.department, 'name', '未知部门')
        cat_name = getattr(self.category, 'name', '未知科目')
        return f"{self.date} - {company_name} - {dept_name} - {cat_name} - {self.amount}"

    @property
    def is_income(self):
        """判断是否为收入"""
        return self.amount > 0

    @property
    def is_expense(self):
        """判断是否为支出"""
        return self.amount < 0


# 聚合报表表（按部门、类目、时间维度聚合）
class AggregatedFinancialReport(models.Model):
    AGGREGATION_TYPE_CHOICES = [
        ('daily', '日报表'),
        ('weekly', '周报表'),
        ('monthly', '月报表'),
        ('quarterly', '季报表'),
        ('annual', '年报表'),
    ]

    aggregation_type = models.CharField(max_length=20, choices=AGGREGATION_TYPE_CHOICES, verbose_name='聚合类型', db_comment='聚合类型')
    period = models.CharField(max_length=50, verbose_name='报表周期', db_comment='报表周期')
    
    # 可选的维度字段
    department = models.ForeignKey(
        Department,
        on_delete=models.CASCADE,
        related_name='aggregated_reports',
        verbose_name='所属部门',
        db_comment='所属部门ID',
        null=True,
        blank=True
    )
    category = models.ForeignKey(
        FinanceCategory,
        on_delete=models.CASCADE,
        related_name='aggregated_reports',
        verbose_name='收支科目',
        db_comment='收支科目ID',
        null=True,
        blank=True
    )
    
    # 聚合数据
    total_income = models.DecimalField(max_digits=15, decimal_places=2, default=0, verbose_name='总收入', db_comment='总收入')
    total_expense = models.DecimalField(max_digits=15, decimal_places=2, default=0, verbose_name='总支出', db_comment='总支出')
    net_profit = models.DecimalField(max_digits=15, decimal_places=2, default=0, verbose_name='净利润', db_comment='净利润')
    transaction_count = models.IntegerField(default=0, verbose_name='交易笔数', db_comment='交易笔数')
    
    # AI分析相关字段
    ai_insights = models.TextField(blank=True, null=True, verbose_name='AI洞察', db_comment='AI洞察')
    ai_suggestions = models.TextField(blank=True, null=True, verbose_name='AI建议', db_comment='AI建议')
    
    generated_at = models.DateTimeField(default=timezone.now, verbose_name='生成时间', db_comment='生成时间')
    generated_by = models.ForeignKey(
        'UserProfile',
        on_delete=models.SET_NULL,
        null=True,
        related_name='aggregated_financial_reports',
        verbose_name='生成者',
        db_comment='生成者ID'
    )

    class Meta:
        db_table = 'mentorx_aggregated_financial_reports'
        verbose_name = '聚合财务报表'
        verbose_name_plural = '聚合财务报表'
        indexes = [
            models.Index(fields=['aggregation_type', 'period'], name='agg_finrep_type_period_idx'),
            models.Index(fields=['department'], name='agg_finrep_department_idx'),
            models.Index(fields=['category'], name='agg_finrep_category_idx'),
        ]
        db_table_comment = '聚合财务报表表'

    def __str__(self) -> str:
        dept_name = self.department.name if self.department else '全部部门'
        cat_name = self.category.name if self.category else '全部科目'
        return f"{self.get_aggregation_type_display()} - {self.period} - {dept_name} - {cat_name}"


# 报表AI解读/分析
class FinancialAnalysis(models.Model):
    RISK_LEVEL_CHOICES = [
        ('low', '低'),
        ('medium', '中'),
        ('high', '高'),
    ]

    report = models.ForeignKey(
        AggregatedFinancialReport,
        on_delete=models.CASCADE,
        related_name='analyses',
        verbose_name='关联报表',
        db_comment='关联报表ID'
    )
    key_insights = models.TextField(verbose_name='关键洞察', db_comment='关键洞察')
    ai_suggestions = models.TextField(verbose_name='AI建议', db_comment='AI建议')
    risk_level = models.CharField(max_length=10, choices=RISK_LEVEL_CHOICES, default='low', verbose_name='风险等级', db_comment='风险等级:low低,medium中,high高')
    created_at = models.DateTimeField(default=timezone.now, verbose_name='创建时间', db_comment='创建时间')

    class Meta:
        db_table = 'mentorx_financial_analysis'
        verbose_name = '财务分析'
        verbose_name_plural = '财务分析'
        ordering = ['-created_at']
        db_table_comment = '财务分析表'

    def __str__(self) -> str:
        return f"{self.report} - {self.get_risk_level_display()}"


# 公司成员表
class CompanyMember(models.Model):
    ROLE_CHOICES = [
        ('founder', '创始人'),
        ('partner', '合伙人'),
        ('employee', '员工'),
        ('advisor', '顾问'),
    ]

    company = models.ForeignKey(
        Company,
        on_delete=models.CASCADE,
        related_name='members',
        verbose_name='所属公司',
        db_comment='所属公司ID'
    )
    user_profile = models.ForeignKey(
        UserProfile,
        on_delete=models.CASCADE,
        related_name='company_memberships',
        verbose_name='成员',
        db_comment='成员ID'
    )
    role = models.CharField(max_length=50, choices=ROLE_CHOICES, verbose_name='角色', db_comment='角色:founder创始人,partner合伙人,employee员工,advisor顾问')
    equity_ratio = models.FloatField(default=0.0, verbose_name='股权比例(%)', db_comment='股权比例百分比')
    join_date = models.DateField(verbose_name='加入日期', db_comment='加入日期')
    is_active = models.BooleanField(default=True, verbose_name='是否在职', db_comment='是否在职')
    created_at = models.DateTimeField(default=timezone.now, verbose_name='创建时间', db_comment='创建时间')

    class Meta:
        db_table = 'mentorx_company_members'
        verbose_name = '公司成员'
        verbose_name_plural = '公司成员'
        unique_together = ['company', 'user_profile']
        db_table_comment = '公司成员表'

    def __str__(self):
        return f"{self.company.name} - {self.user_profile}"


# 智能财务报表表
class SmartFinancialReport(models.Model):
    REPORT_TYPE_CHOICES = [
        ('monthly', '月度报表'),
        ('quarterly', '季度报表'),
        ('annual', '年度报表'),
    ]

    company = models.ForeignKey(
        Company,
        on_delete=models.CASCADE,
        related_name='smart_reports',
        verbose_name='所属公司',
        db_comment='所属公司ID'
    )
    report_type = models.CharField(max_length=20, choices=REPORT_TYPE_CHOICES, verbose_name='报表类型', db_comment='报表类型:monthly月度,quarterly季度,annual年度')
    period = models.CharField(max_length=50, verbose_name='报表周期', db_comment='报表周期')
    revenue = models.DecimalField(max_digits=15, decimal_places=2, default=0, verbose_name='营收', db_comment='营收')
    expenses = models.DecimalField(max_digits=15, decimal_places=2, default=0, verbose_name='支出', db_comment='支出')
    profit = models.DecimalField(max_digits=15, decimal_places=2, default=0, verbose_name='利润', db_comment='利润')
    report_data = models.JSONField(default=dict, verbose_name='报表数据', db_comment='报表数据JSON')
    ai_insights = models.TextField(blank=True, null=True, verbose_name='AI洞察', db_comment='AI洞察')
    generated_by = models.ForeignKey(
        UserProfile,
        on_delete=models.SET_NULL,
        null=True,
        related_name='smart_financial_reports',
        verbose_name='生成者',
        db_comment='生成者ID'
    )
    created_at = models.DateTimeField(default=timezone.now, verbose_name='创建时间', db_comment='创建时间')

    class Meta:
        db_table = 'mentorx_smart_financial_reports'
        verbose_name = '智能财务报表'
        verbose_name_plural = '智能财务报表'
        ordering = ['-created_at']
        db_table_comment = '智能财务报表表'

    def __str__(self):
        return f"{self.company.name} - {self.get_report_type_display()} - {self.period}"
